package com.woniuxy.project.campus.exception;

import cn.hutool.json.JSONUtil;

import com.woniuxy.project.campus.util.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//配置网关全局异常处理器
@Component
public class GloableExceptionHandler implements ErrorWebExceptionHandler {
        @Override
        public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
            return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
                ex.printStackTrace();
                Result<Object> objectResult = new Result<Object>();
                objectResult.setCode(500);
                System.out.println(ex.getMessage());
                System.out.println(exchange);
                System.out.println(ex);
                objectResult.setMessage(ex.getMessage());
                //对象转换为json字符串
                String jsonResult = JSONUtil.toJsonStr(objectResult);
                return  exchange.getResponse().bufferFactory().wrap(jsonResult.getBytes());
            }));
        }
}
